<template>
  <div class="overlay">
    <div class="salary-container">
      <h1>工资详情</h1>
      <p class="salary-month">
        选择年月份：
        <select v-model="selectedMonth" class="month-select">
          <option v-for="month in availableMonths" :key="month" :value="month">
            {{ month }}
          </option>
        </select>
      </p>

      <p v-if="loading">正在加载数据...</p>
      <p v-else-if="error" style="color: red;">{{ error }}</p>

      <div v-else>
        <!-- 突出显示总工资 -->
        <div class="total-salary-box">
          您该月的总工资为：<span class="highlight">{{ salaryDetails.totalSalary }}</span>
        </div>

        <!-- 显示年终奖金 -->
        <div class="annual-bonus-box" v-if="annualBonus">
          您上一年的年终奖金为：<span class="highlight">{{ annualBonus }}</span>
        </div>

        <!-- 激励语句 -->
        <p class="incentive-text" v-if="incentiveMessage">{{ incentiveMessage }}</p>

        <!-- 工资细则说明 -->
        <p class="detail-title">工资细则：</p>

        <!-- 工资明细表格 -->
        <table class="salary-table">
          <thead>
            <tr>
              <th>基本工资</th>
              <th>考勤金额</th>
              <th>加班津贴</th>
              <th>总计</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{{ salaryDetails.base }}</td>
              <td>{{ salaryDetails.attendance }}</td>
              <td>{{ salaryDetails.allowance }}</td>
              <td>{{ salaryDetails.totalSalary }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import axios from '../axios/index.js';
import { useUserStore } from '../store/UserStore.js';

export default {
  name: 'Salary',
  setup() {
    const salaryDetails = ref({
      base: 0,
      attendance: 0,
      allowance: 0,
      totalSalary: 0,
    });

    const loading = ref(false);
    const error = ref(null);
    const selectedMonth = ref(''); // 当前选中的月份
    const availableMonths = ref([]); // 可选的年月列表

    const userStore = useUserStore(); // 获取当前用户信息

    const incentiveMessage = computed(() => {
      const total = parseFloat(salaryDetails.value.totalSalary);
      if (total < 10000) return '未来无限可能，努力升职加薪！';
      else if (total >= 10000 && total <= 20000) return '优秀的员工呀，请继续努力，更高的薪资在等着你！';
      else if (total > 20000) return '公司的核心员工，未来一起创造辉煌吧！';
      return '';
    });

    // 年终奖金
    const annualBonus = ref(0);

    // 获取年终奖金
    const calculateAnnualBonus = async () => {
      try {
        const userId = userStore.curUser?.user_id;
        if (!userId) throw new Error("未找到当前用户ID");

        // 请求员工上一年的年终奖金
        const response = await axios.post('/salary/annual-summary', { userId });
        annualBonus.value = parseFloat(response.data.data.annualBonus).toFixed(2);
      } catch (err) {
        console.error('获取年终奖金数据失败:', err);
        error.value = '无法获取年终奖金数据，请稍后再试。';
      }
    };

    // 获取当前时间上个月的年月字符串
    const getLastMonth = () => {
      const date = new Date();
      date.setMonth(date.getMonth() - 1);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    };

    onMounted(async () => {
      loading.value = true;
      error.value = null;

      try {
        const userId = userStore.curUser?.user_id;
        if (!userId) throw new Error("未找到当前用户ID");

        // 请求用户所有可查询的年月列表
        const response = await axios.post('/salary/months', { userId });
        availableMonths.value = response.data.data;
        selectedMonth.value = getLastMonth(); // 默认选中上个月

        // 加载对应月份的工资数据
        await loadSalaryData(userId, selectedMonth.value);

        // 获取年终奖金
        await calculateAnnualBonus();
      } catch (err) {
        console.error('初始化失败:', err);
        error.value = '无法加载薪资数据或可选年月。';
      } finally {
        loading.value = false;
      }
    });

    // 监听 selectedMonth 改变并重新加载工资数据
    watch(selectedMonth, async (newMonth) => {
      const userId = userStore.curUser?.user_id;
      if (userId && newMonth) {
        await loadSalaryData(userId, newMonth);
      }
    });

    // 封装加载工资数据的方法
    const loadSalaryData = async (userId, month) => {
      try {
        const response = await axios.post('/salary/load', { userId, month });
        const r = response.data;
        salaryDetails.value = {
          base: r.data.baseSalary,
          attendance: r.data.attendanceMoney,
          allowance: r.data.allowanceMoney,
          totalSalary: r.data.totalSalary
        };
      } catch (err) {
        console.error('获取工资数据失败:', err);
        error.value = '无法获取工资数据，请稍后再试。';
      }
    };

    return {
      salaryDetails,
      selectedMonth,
      availableMonths,
      loading,
      error,
      incentiveMessage,
      annualBonus,
    };
  }
};
</script>

<style scoped>
/* 覆盖层：全屏遮罩 + 居中容器 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #e0ecff, #f5fcff);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 900;
}

/* 工资卡片样式 */
.salary-container {
  padding: 40px;
  background-color: #f9f9f9;
  max-width: 800px;
  width: 100%;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  z-index: 901;
  position: relative;
  margin: 20px;
}

h1 {
  text-align: center;
}

/* 突出显示总工资 */
.salary-month,
.total-salary-box {
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  text-align: center;
}

/* 显示年终奖金 */
.annual-bonus-box {
  font-size: 1.2rem; /* 调整字体大小 */
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  text-align: center;
}

.highlight {
  color: #e67e22;
  font-size: 2.8rem;
}

.incentive-text {
  text-align: center;
  font-size: 1.3rem;
  color: #226ae6;
  margin-top: 10px;
  font-weight: bold;
}

/* 工资细则说明文字 */
.detail-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #555;
  margin-bottom: 10px;
}

/* 表格样式优化 */
.salary-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  margin-top: 30px;
}

.salary-table thead {
  background-color: #007bff;
  color: white;
}

.salary-table th,
.salary-table td {
  font-size: 1.3rem;
  padding: 12px;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

.salary-table tbody tr:nth-child(even) {
  background-color: #f2f2f2;
}

.month-select {
  font-size: 1.2rem;
  padding: 5px 10px;
  margin-left: 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
}
</style>